<?php


namespace App\Http\Controllers;


use App\Models\User;
use Illuminate\Http\Request;

class LoginController extends Controller
{
    public function login(Request $request)
    {
        $request->validate([
            'code'=>'required|string',
            'iv'=>'required|string',
            'encryptedData'=>'required|string'
        ]);

        $code = $request->post('code');
        $iv = $request->post('iv');
        $encryptedData = $request ->post('encryptedData');

        $app = \EasyWeChat::miniProgram();
        $session = $app ->auth->session($code);
//        print_r($session);
        if(!isset($session['openid'])) return $this ->fail('登陆失败|session获取失败');

        $userInfo = $app->encryptor->decryptData($session['session_key'], $iv, $encryptedData);

        $user = User::updateOrCreate(
            ['openid'=>$userInfo['openId']],
            [
                'nickname'      => $userInfo['nickName'],
                'unionid'       => $userInfo['unionId'],
                'gender'        => $userInfo['gender'],
                'city'          => $userInfo['city'],
                'province'      => $userInfo['province'],
                'country'       => $userInfo['country'],
                'avatar_url'    => $userInfo['avatarUrl']
            ]
        );

        $ret = array(
            'token' => $userInfo['openId'],
            'user' => $user
        );

        return res($ret);
    }
}
